﻿using I_Authorization.Domains;
using I_Authorization.Domains.Organization;
using I_Authorization.Infrastructure.Interface;
using I_Authorization.Read.API.Application.Commands.Employee;
using MediatR;
using System.Linq;

namespace I_Authorization.Read.API.Application.CommandHandlers.Employee
{
    /// <summary>
    /// 人员联查部门信息显示
    /// </summary>
    public class EmployeeShowCommandHandlers : IRequestHandler<EmployeeShowCommand,Page<EmployeeInfo>>
    {
        private readonly IEmployeeRepository _employeeRepository;

        public EmployeeShowCommandHandlers(IEmployeeRepository employeeRepository)
        {
            _employeeRepository = employeeRepository;
        }



        /// <summary>
        /// 人员显示以及分页
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Page<EmployeeInfo>> Handle(EmployeeShowCommand request, CancellationToken cancellationToken)
        {
            //throw new NotImplementedException();
            var list = await _employeeRepository.GetAsync(x => x.IsDel == true);
            IQueryable<EmployeeInfo> filtList = list.AsQueryable();

            if(!string.IsNullOrEmpty(request.EmployeeName))
            {
                filtList = filtList.Where(x => x.EmployeeName.Contains(request.EmployeeName));
            }

            if (!string.IsNullOrEmpty(request.EmployeeState))
            {
                filtList = filtList.Where(x => x.EmployeeState.Contains(request.EmployeeState));
            }
            if (request.DepartId > 0)
            {
                filtList = filtList.Where(x => x.DepartId == request.DepartId);
            }

            var pageData = filtList.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

            int totalCount = list.Count();

            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);

            //list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            return new Page<EmployeeInfo>
            {
                tatalCount=totalCount,
                pageCount=pageCount,
                Data = pageData.ToList(),
            };
        }
    }
}
